package com.chuanyekeji.aokai.Controller;

import com.chuanyekeji.aokai.Mapper.InformationMapper;
import com.chuanyekeji.aokai.Util.FileUtil;
import com.chuanyekeji.aokai.Config.ReadPathConfig;
import com.chuanyekeji.aokai.Util.ReturnData;
import com.google.gson.Gson;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class FileController {

    @Autowired
    ReadPathConfig readPathConfig;

    @Autowired
    InformationMapper informationMapper;

    /**
     * 文件上传
     * @param imgFile
     * @return
     */
    @RequestMapping("upFile")
    String upFile(@RequestParam(value = "imgFile",required = false) MultipartFile imgFile,String dir) {
        //封装返回数据
        Map<String,Object> data = new HashMap<>();
        Gson gson = new Gson();
        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getImage());
        firstImagePath = file.getAbsolutePath() + "/";
        String fileName = imgFile.getOriginalFilename();
        //随机码
        String imgCode = UUID.randomUUID().toString();
        //获取文件后缀名
        String[] str = fileName.split("\\.");
        String imageName = imgCode + "." + str[1];
        System.out.println(firstImagePath);
        try {
            //保存图片
            if(FileUtil.uploadFile(imgFile.getBytes(), firstImagePath,imageName)) {
                data.put("error",0);
                data.put("url",readPathConfig.getFirstPage() + readPathConfig.getImage() + "/" + imageName);
            } else {
                data.put("error",1);
                data.put("message","error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return gson.toJson(data);
    }

    /**
     * 将资讯内容保存为网页
     * @param content
     * @return
     */
    @RequestMapping("handleFile")
    String handleFile(@Param("content") String content) {
        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getInformation());
        if(!file.exists()) {
            file.mkdirs();
        }
        firstImagePath = file.getAbsolutePath() + "/";
        //随机码
        String imgCode = UUID.randomUUID().toString();
        String fileName = imgCode + ".html";
        try {
            //文件输出流
            FileOutputStream fileoutputstream = new FileOutputStream(firstImagePath + fileName);
            byte[] bytes = content.getBytes();
            fileoutputstream.write(bytes);
            fileoutputstream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ReturnData.success(firstImagePath + fileName);
    }

    /**
     * 上传图片
     * @param image
     * @return
     */
    @RequestMapping("upImage")
    String upImage(@RequestParam(value = "image",required = false) MultipartFile image) {
        //封装返回数据
        Map<String,Object> data = new HashMap<>();
        Gson gson = new Gson();
        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getImage());
        firstImagePath = file.getAbsolutePath() + "/";
        String fileName = image.getOriginalFilename();
        //随机码
        String imgCode = UUID.randomUUID().toString();

        //获取点最后出现的位置
        int lastIndex = fileName.lastIndexOf(".");
        //字符串最后的位置
        int endIndex = fileName.length();
        // 获取文件后缀名
        String str = fileName.substring(lastIndex,endIndex);
        String imageName = imgCode + str;
        try {
            //保存图片
            if(FileUtil.uploadFile(image.getBytes(), firstImagePath,imageName)) {
                data.put("code",0);
                data.put("url",readPathConfig.getImage() + "/" + imageName);
            } else {
                data.put("code",1);
                data.put("message","error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return gson.toJson(data);
    }

    /**
     * 上传图片
     * @param images
     * @return
     */
    @RequestMapping("upImages")
    String upImages(@RequestParam(value = "image",required = false) MultipartFile[] images) {
        //封装返回数据
        Map<String,Object> data = new HashMap<>();
        Gson gson = new Gson();
        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getImage());
        firstImagePath = file.getAbsolutePath() + "/";
        String url = "";
        for(int i=0;i<images.length;i++) {
            String fileName = images[i].getOriginalFilename();
            //随机码
            String imgCode = UUID.randomUUID().toString();

            //获取点最后出现的位置
            int lastIndex = fileName.lastIndexOf(".");
            //字符串最后的位置
            int endIndex = fileName.length();
            // 获取文件后缀名
            String str = fileName.substring(lastIndex,endIndex);
            String imageName = imgCode + str;
            try {
                //保存图片
                if(FileUtil.uploadFile(images[i].getBytes(), firstImagePath,imageName)) {
                    data.put("code",0);
                    url += readPathConfig.getImage() + "/" + imageName + ";";
                } else {
                    data.put("code",1);
                    data.put("message","error");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        data.put("url",url);
        return gson.toJson(data);
    }
}